Creazione di un formattatore di campo
Il modulo del formattatore di campo formatta i dati del campo per la visualizzazione all’utente finale. I formattatori di campo sono definiti come plugin, quindi è consigliato leggere l’API dei plugin prima di iniziare a scrivere un nuovo formattatore di campo.
Classe del formattatore di campo
Percorso file: /modules/random/src/Plugin/Field/FieldFormatter/RandomDefaultFormatter.php
<?php namespace Drupal\random\Plugin\Field\FieldFormatter; use Drupal\Core\Field\FormatterBase; use Drupal\Core\Field\FieldItemListInterface; /** * Implementazione del plugin 'Random_default' formatter. * * @FieldFormatter( * id = "Random_default", * label = @Translation("Random text"), * field_types = { * "Random" * } * ) */ class RandomDefaultFormatter extends FormatterBase { /** * {@inheritdoc} */ public function settingsSummary() { $summary = []; $summary[] = $this->t('Displays the random string.'); return $summary; } /** * {@inheritdoc} */ public function viewElements(FieldItemListInterface $items, $langcode) { $element = []; foreach ($items as $delta => $item) { // Renderizza ogni elemento come markup. $element[$delta] = ['#markup' => $item->value]; } return $element; } }
Impostazioni del formattatore
Se il tuo formattatore richiede impostazioni personalizzate di visualizzazione, occorre seguire tre passaggi:
- Sovrascrivere PluginSettingsBase::defaultSettings() per definire valori predefiniti
- Creare uno schema di configurazione per le impostazioni personalizzate
- Creare un form per consentire agli utenti di modificare le impostazioni
Passo 1: Sovrascrivere PluginSettingsBase::defaultSettings() per definire valori predefiniti
/** * {@inheritdoc} */ public static function defaultSettings() { return [ // Definisce un’impostazione 'text_length' con valore predefinito 'short' 'text_length' => 'short', ] + parent::defaultSettings(); }
Passo 2. Creare lo schema di configurazione per le impostazioni
Lo schema di configurazione si trova nel seguente file:
[MODULE ROOT]/config/schema/[MODULE_NAME].schema.yml
In questo file si descrive il tipo di dati delle impostazioni create in defaultSettings():
Il passo 1 ha creato un’impostazione chiamata 'text_length' che memorizza una stringa. Lo schema sarà così:
field.formatter.settings.[FORMATTER ID]: type: mapping label: 'FORMATTER NAME text length' mapping: text_length: type: string label: 'Text Length'
Passo 3: Creare il form per permettere agli utenti di modificare le impostazioni
Il form che consente di modificare i valori viene creato sovrascrivendo FormatterBase::settingsForm().
Non dimenticare di aggiungere lo spazio dei nomi di FormState all’inizio del file PHP.
use Drupal\Core\Form\FormStateInterface;
/** * {@inheritdoc} */ public function settingsForm(array $form, FormStateInterface $form_state) { $form['text_length'] = [ '#title' => $this->t('Text length'), '#type' => 'select', '#options' => [ 'short' => $this->t('Short'), 'long' => $this->t('Long'), ], '#default_value' => $this->getSetting('text_length'), ]; return $form; }
Uso di #ajax nei form delle impostazioni
L’uso di #ajax nei form delle impostazioni non è semplice, poiché la porzione di form creata in settingsForm() non è alla radice ma profondamente annidata. Nell’esempio seguente il form ha due impostazioni: display_type, che può essere “label” o “entity”, ed entity_display_mode, che può essere “full” o “teaser”. L’opzione entity_display_mode appare solo se display_type è impostato su “entity”.
public function settingsForm(array $form, FormStateInterface $form_state) { $form['display_type'] = [ '#title' => $this->t('Display Type'), '#type' => 'select', '#options' => [ 'label' => $this->t('Label'), 'entity' => $this->t('Entity'), ], '#default_value' => $this->getSetting('display_type'), '#ajax' => [ 'wrapper' => 'private_message_thread_member_formatter_settings_wrapper', 'callback' => [$this, 'ajaxCallback'], ], ]; $form['entity_display_mode'] = [ '#prefix' => '<div id="private_message_thread_member_formatter_settings_wrapper">', '#suffix' => '</div>', ]; $field_name = $this->fieldDefinition->getItemDefinition()->getFieldDefinition()->getName(); $setting_key = 'display_type'; if($value = $form_state->getValue(['fields', $field_name, 'settings_edit_form', 'settings', $setting_key])) { $display_type = $value; } else { $display_type = $this->getSetting('display_type'); } if($display_type == 'entity') { $form['entity_display_mode']['#type'] = 'select'; $form['entity_display_mode']['#title'] = $this->t('View mode'); $form['entity_display_mode']['#options'] = [ 'full' => $this->t('Full'), 'teaser' => $this->t('Teaser'), ]; $form['entity_display_mode']['#default_value'] = $this->getSetting('entity_display_mode'); } else { $form['entity_display_mode']['#markup'] = ''; } return $form; }
Poi si crea la callback ajax che restituisce l’elemento corretto:
public function ajaxCallback(array $form, FormStateInterface $form_state) { $field_name = $this->fieldDefinition->getItemDefinition()->getFieldDefinition()->getName(); $element_to_return = 'entity_display_mode'; return $form['fields'][$field_name]['plugin']['settings_edit_form']['settings'][$element_to_return]; }
Dependency Injection nei formattatori di campo
Usare la Dependency Injection in un formattatore richiede tre passaggi:
- Implementare ContainerFactoryPluginInterface
- Implementare ContainerFactoryPluginInterface::create()
- Sovrascrivere FormatterBase::__construct()
1) Implementare ContainerFactoryPluginInterface
use Drupal\Core\Plugin\ContainerFactoryPluginInterface; class MyFormatter extends FormatterBase implements ContainerFactoryPluginInterface {
2) Implementare ContainerFactoryPluginInterface::create()
Esempio che inietta il servizio entity.manager nel formattatore:
use Symfony\Component\DependencyInjection\ContainerInterface; public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) { return new static( $plugin_id, $plugin_definition, $configuration['field_definition'], $configuration['settings'], $configuration['label'], $configuration['view_mode'], $configuration['third_party_settings'], // Aggiungi qui i servizi da iniettare $container->get('entity.manager') ); }
3) Sovrascrivere FormatterBase::__construct()
Sovrascrivi __construct() in FormatterBase, richiama parent::__construct() e memorizza il servizio come proprietà della classe:
use Drupal\Core\Field\FieldDefinitionInterface; /** * Servizio entity manager * * @var \Drupal\Core\Entity\EntityManagerInterface */ protected $entityManager; public function __construct($plugin_id, $plugin_definition, FieldDefinitionInterface $field_definition, array $settings, $label, $view_mode, array $third_party_settings, EntityManagerInterface $entityManager) { parent::__construct($plugin_id, $plugin_definition, $field_definition, $settings, $label, $view_mode, $third_party_settings); $this->entityManager = $entityManager; }
Ora puoi usare $this->entityManager ovunque nella classe del formattatore.